package cn.sccdlg.springboot.controller;

import cn.sccdlg.springboot.model.User;
import cn.sccdlg.springboot.servcie.UserService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author RaoShuang
 * @emil 991207823@qq.com
 * @date 2020/5/8 21:37
 */
@Controller
public class UserController {

    @Reference
    private UserService userService;
    @RequestMapping("/index")
    public String index(@RequestParam(value = "curPage",required = false) Integer curPage, Model model) {
        //每页展示5条数据(写死固定了)
        int pageSize = 5;
        //当前页数
        if (null == curPage || curPage < 1) {
            curPage = 1;
        }
        //总数.
        int totalRows = userService.getUserByTqtal();
        //计算分页页数
        int totalPages = totalRows / pageSize;
        //有可能有余数
        int left = totalRows % pageSize;
        if(left>0){
            totalPages = totalPages + 1;
        }
        if (curPage > totalPages) {
            curPage = totalPages;
        }
        //计算查询的开始
        int startRow = (curPage - 1) * pageSize;
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("startRow", startRow);
        paramMap.put("pageSize", pageSize);

        List<User> userList = userService.getUserByPage(paramMap);
        model.addAttribute("userList", userList);
        model.addAttribute("curPage", curPage);
        model.addAttribute("totalPages", totalPages);
        return "index";
    }

    /**
     * 去添加用户
     * @return
     */
    @RequestMapping("/user/toAddUser")
    public String toAddUser() {
        return "addUser";
    }

    /**
     * 添加用户/修改用户
     * @return
     */
    @RequestMapping("/user/addUser")
    public String addUser(User user) {
        Integer id = user.getId();
        if (id ==null) {
            int count = userService.addUser(user);//添加用户
            System.out.println(" 新增数据条数："+ count);
        } else {
            int count = userService.updateUser(user);//修改用户
            System.out.println(" 修改数据条数："+ count);
        }
        return "redirect:/index";
    }

    /**
     * 去修改用户
     * @return
     */
    @RequestMapping("/user/toUpdate")
    public String toUpdateUser(@RequestParam Integer id,Model model) {
        User user = userService.getUserById(id);
        model.addAttribute("user",user);
        return "addUser";
    }

    /**
     * 根据用户id删除用户
     * @param id
     * @return
     */
    @RequestMapping("/user/delete")
    public String deleteUser(@RequestParam Integer id) {
        int count = userService.deleteUser(id);
        System.out.println(" 删除数据条数："+ count);
        return "redirect:/index";
    }


}
